package com.lemner.motion.activity;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.lemner.motion.R;
import com.lemner.motion.base.BaseActivity;
import com.lemner.motion.util.DensityUtil;
import com.lemner.motion.util.FullScreen;
import com.lemner.motion.util.SystemUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.amap.api.col.sl2.x.i;
import static com.lemner.motion.util.DensityUtil.dip2px;

public class MainActivity extends BaseActivity implements AMap.OnMyLocationChangeListener, View.OnTouchListener {

    private MapView mMapView = null;
    private AMap aMap = null;
    private PolylineOptions polylineOptions, pausepolylineOptions;
    private TextView tv_countdown, btn_pause1, tv_time, btn_finish, btn_continue, tv_distance, tv_speed, tv_mode;
    private ImageButton ib_changemode;
    private LinearLayout layout_keepout, ll_pause1, ll_finish, ll_continue, ll_sum;
    private ImageView iv_pic;
    private Boolean isFirstLocation = true, modeflag = true, flag = true;
    private double latitude1, latitude2, longitude1, longitude2, distance = 0, peispeed = 0, speed = 0;
    private long time1, time2;
    private int time = 0;
    private int startY = 0, dySum = 0;
    private float llsum_height = 0;
    private List<Integer> colors = new ArrayList<Integer>();
    private List<LatLng> latLngs = new ArrayList<LatLng>();

    private List<LatLng> pauselatLngs = new ArrayList<LatLng>();

    private List<Marker> marker = new ArrayList<Marker>();
    private List<Circle> circle = new ArrayList<Circle>();
    private List<Boolean> arrive = new ArrayList<Boolean>();
    private Boolean isthrough = false;

    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private NotificationManager notificationManager = null;
    private AMapLocationClient mlocationClient = null;
    boolean isCreateChannel = false;

    private List<String> list = new ArrayList<String>();
    private List<LatLng> latLngList = new ArrayList<LatLng>();
    private long exitTime = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutFile() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        FullScreen.fullScreen(this, 0x33131313);
        mMapView = (MapView) findViewById(R.id.map);
        tv_countdown = (TextView) findViewById(R.id.tv_countdown);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_mode = (TextView) findViewById(R.id.tv_mode);
        iv_pic = (ImageView) findViewById(R.id.iv_pic);
        ib_changemode = (ImageButton) findViewById(R.id.ib_changemode);
        layout_keepout = (LinearLayout) findViewById(R.id.layout_keepout);
        ll_pause1 = (LinearLayout) findViewById(R.id.ll_pause1);
        ll_finish = (LinearLayout) findViewById(R.id.ll_finish);
        btn_pause1 = (TextView) findViewById(R.id.btn_pause1);
        ll_continue = (LinearLayout) findViewById(R.id.ll_continue);
        ll_sum = (LinearLayout) findViewById(R.id.ll_sum);
        btn_finish = (TextView) findViewById(R.id.btn_finish);
        btn_continue = (TextView) findViewById(R.id.btn_continue);
        tv_distance = (TextView) findViewById(R.id.tv_distance);
        tv_speed = (TextView) findViewById(R.id.tv_speed);
        btn_pause1.setVisibility(View.INVISIBLE);
        iv_pic.setVisibility(View.INVISIBLE);
        initMap();
        distance = 0;
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        ib_changemode.setOnClickListener(this);
        btn_pause1.setOnTouchListener(this);
        btn_finish.setOnClickListener(this);
        btn_continue.setOnClickListener(this);
    }


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                time = msg.arg1;
                tv_time.setText(String.format("%02d:%02d:%02d", time / 3600, time / 60 % 60, time % 60));
            }
            super.handleMessage(msg);
        }
    };

    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if (flag) {
                time += 1;
                Message message = new Message();
                message.arg1 = time;
                message.what = 1;
                handler.sendMessage(message);
            }
        }
    };


    @Override
    public void initData() {
        tv_countdown.setText("3");
        //3,2,1倒计时
        final CountDownTimer countDownTimer = new CountDownTimer(4000, 5) {
            @Override
            public void onTick(long l) {
                tv_countdown.setText(((l + 1) / 1000) + "");
                tv_countdown.setTextSize(TypedValue.COMPLEX_UNIT_PX, dip2px(MainActivity.this, (l - l / 1000 * 1000) / 13 + 75));
            }
            @Override
            public void onFinish() {
                tv_countdown.setVisibility(View.INVISIBLE);
                btn_pause1.setVisibility(View.VISIBLE);
                iv_pic.setVisibility(View.VISIBLE);
                if (flag) {
                    timer.schedule(timerTask, 0, 1000);
                }
            }
        };
        countDownTimer.start();

        list = getIntent().getStringArrayListExtra("waylist");
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);//根据逗号分隔到List1数组中
            String str2 = str.replace(" ", "");//去掉所用空格
            List<String> list1 = Arrays.asList(str2.split(","));
            LatLng latLng = new LatLng(DensityUtil.convertToDouble(list1.get(0), 0), DensityUtil.convertToDouble(list1.get(list1.size() - 1), 0));
            latLngList.add(latLng);
            marker.add(aMap.addMarker(new MarkerOptions().position(latLngList.get(i)).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(), R.drawable.wayflag)))));
            circle.add(aMap.addCircle(new CircleOptions().center(latLngList.get(i)).radius(10).fillColor(Color.argb(128, 0, 0, 255)).strokeColor(Color.argb(128, 0, 0, 0))));
            arrive.add(false);
        }
    }


    public void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        mlocationClient = new AMapLocationClient(this);
        MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(1000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
        aMap.setOnMyLocationChangeListener(this);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        UiSettings mUiSettings;//定义一个UiSettings对象
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setCompassEnabled(true);//开启指南针
        mUiSettings.setScaleControlsEnabled(true);//开启比例尺
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_changemode:
                if (modeflag) {
                    layout_keepout.setBackgroundResource(R.drawable.shape_gradient_main0);
                    tv_mode.setText("地图模式");
                    modeflag = false;
                } else {
                    layout_keepout.setBackgroundResource(R.drawable.shape_gradient_main);
                    tv_mode.setText("跑步模式");
                    modeflag = true;
                }
                break;
            case R.id.btn_finish:
                Bundle bundle = new Bundle();
                bundle.putSerializable("colors", (Serializable) colors);
                bundle.putSerializable("latLngs", (Serializable) latLngs);
                startActivity(new Intent(MainActivity.this, RecordActivity.class).putExtra("distance", distance).putExtra("time", time).putExtra("peispeed", peispeed).putExtra("isthrough", isthrough).putExtras(bundle));
                finish();
                break;
            case R.id.btn_continue:
                mySetY(0, llsum_height, llsum_height);
                flag = true;
                break;
        }
    }


    @Override
    public void onMyLocationChange(android.location.Location location) {
        if (location.getLatitude() != 0 && location.getLongitude() != 0) {//避免定位到非洲西海岸
            latitude1 = location.getLatitude();
            longitude1 = location.getLongitude();
            if (flag) {
                if (isFirstLocation) {
                    latLngs.add(new LatLng(location.getLatitude(), location.getLongitude()));
                    polylineOptions = new PolylineOptions();
                    //aMap.addPolyline(polylineOptions);
                    time1 = time2 = System.currentTimeMillis();
                    isFirstLocation = false;
                    MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
                    myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
                    myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
                    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
                    aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
                } else {
                    time1 = time2;
                    time2 = System.currentTimeMillis();
                    distance += AMapUtils.calculateLineDistance(new LatLng(latitude1, longitude1), new LatLng(latitude2, longitude2)) / 1000;
                    speed = (AMapUtils.calculateLineDistance(new LatLng(latitude1, longitude1), new LatLng(latitude2, longitude2))) / ((double) (time2 - time1) / 1000);
                    if (speed != 0) {
                        latLngs.add(new LatLng(location.getLatitude(), location.getLongitude()));
                        if (latLngs.size() > 2)
                            polylineOptions.add(latLngs.get(latLngs.size() - 1)).width(10f).useGradient(true);
                        if (speed < 2) {
                            colors.add(0xffff0000);
                        } else if (speed < 5) {
                            colors.add(0xffffff00);
                        } else {
                            colors.add(0xff00ff00);
                        }
                        polylineOptions.colorValues(colors);
                        aMap.addPolyline(polylineOptions);
                        for (int i = 0; i < latLngList.size(); i++) {
                            if (AMapUtils.calculateLineDistance(new LatLng(location.getLatitude(), location.getLongitude()), latLngList.get(i)) <= 10) {
                                circle.get(i).setFillColor(Color.argb(128, 0, 255, 0));
                                arrive.set(i, true);
                                Vibrator vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
                                vibrator.vibrate(500);
                            }
                        }
                        if (arrive.get(0) && arrive.get(1) && arrive.get(2)) {
                            isthrough = true;
                            // marker.get(2).getOptions().snippet("已顺利通过三个点");
                            // marker.get(2).showInfoWindow();
                        }
                    }
                    tv_distance.setText(String.format("%.2f公里", distance));
                    peispeed = 0;
                    if (distance > 0.1)
                        peispeed = time / 60.0 / distance;
                    tv_speed.setText(String.format("%.2f配速", peispeed));
                }
            } else {
                distance += 0;
                polylineOptions.add(new LatLng(location.getLatitude(), location.getLongitude())).width(10f).useGradient(true);
                colors.add(0xff888888);
                polylineOptions.colorValues(colors);
                aMap.addPolyline(polylineOptions);
            }
            latitude2 = latitude1;
            longitude2 = longitude1;
        }
    }
    @SuppressLint("NewApi")
    private Notification buildNotification() {
        Notification.Builder builder = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        builder.setSmallIcon(R.drawable.clock)
                .setContentTitle("运动校园")
                .setContentText("正在后台运行")
                .setWhen(System.currentTimeMillis());

        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        //销毁后台定位
        mlocationClient.disableBackgroundLocation(true);
        if (null != timer)
            timer.cancel();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ll_sum.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ll_sum.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                llsum_height = ll_sum.getMeasuredHeight();
                if (flag) {
                    mySetY(0, llsum_height, llsum_height);
                } else {
                    mySetY(llsum_height, 0, 0);
                }
            }
        });
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //启动后台定位
        if (null != mlocationClient)
            mlocationClient.enableBackgroundLocation(2001, buildNotification());
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (flag) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 获取手指按下的坐标
                    startY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    // 获取手指移动到了哪个点的坐标
                    int movingY = (int) event.getRawY();
                    // 相对于上一个点，手指在X和Y方向分别移动的距离
                    int dy = movingY - startY;
                    dySum += dy;
                    if (dySum < 0) {
                        dySum -= dy;
                        dy = 0;
                    }
                    // 获取控件上一次上 下 左 右各边与父控件的距离
                    ll_pause1.layout(ll_pause1.getLeft(), ll_pause1.getTop() + dy, ll_pause1.getRight(), ll_pause1.getBottom() + dy);
                    ll_finish.layout(ll_finish.getLeft(), ll_finish.getTop() - dy, ll_finish.getRight(), ll_finish.getBottom() - dy);
                    ll_continue.layout(ll_continue.getLeft(), ll_continue.getTop() - dy, ll_continue.getRight(), ll_continue.getBottom() - dy);
                    // 本次移动的结尾作为下一次移动的开始
                    startY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    if (dySum > llsum_height - 220) {
                        mySetY(llsum_height, 0, 0);
                        flag = false;
                    } else {
                        mySetY(0, llsum_height, llsum_height);
                    }
                    dySum = 0;
                    break;
            }
        }
        return true;
    }

    public void mySetY(float a, float b, float c) {
        if (a == 0) {
            ll_continue.setVisibility(View.INVISIBLE);
            ll_finish.setVisibility(View.INVISIBLE);
            ll_pause1.setVisibility(View.VISIBLE);
        } else {
            ll_pause1.setVisibility(View.INVISIBLE);
            ll_continue.setVisibility(View.VISIBLE);
            ll_finish.setVisibility(View.VISIBLE);
        }
        ll_pause1.setY(a);
        ll_continue.setY(b);
        ll_finish.setY(c);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("请先按计划跑完");
                exitTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}